package com.snail.utils;

import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author 蔡徐坤
 * @Date 2025/8/15 14:24
 * @Description: TODO
 */
@Component
public class TokenStore {

    public static class Entry {
        public String loginId;
        public long expireAt; // epoch seconds
    }

    private final Map<String, Entry> store = new ConcurrentHashMap<>();

    public String create(String loginId, long ttlSeconds) {
        String token = "atk_" + UUID.randomUUID().toString().replace("-", "");
        Entry e = new Entry();
        e.loginId = loginId;
        e.expireAt = Instant.now().getEpochSecond() + ttlSeconds;
        store.put(token, e);
        return token;
    }

    public String getLoginIdByToken(String token) {
        Entry e = store.get(token);
        if (e == null) return null;
        if (Instant.now().getEpochSecond() > e.expireAt) {
            store.remove(token);
            return null;
        }
        return e.loginId;
    }
}
